﻿using System;
using System.Text;
using System.Web.Mvc;

namespace Safal.IncidentTracker.WebUI.HtmlHelpers {
    public static class PagingHelpers {
        public static MvcHtmlString PageLinks(this HtmlHelper htmlHelper, IPagedList pagedList, Func<int, string> pageUrl)
        {
            StringBuilder result = new StringBuilder();

            if (pagedList.HasPreviousPage)
            {
                TagBuilder tag = new TagBuilder("a");
                tag.InnerHtml = "prev";
                tag.Attributes.Add("href", pageUrl.Invoke(pagedList.PreviousPage));
                result.AppendLine(tag.ToString());
            }

            for (int i = 1; i <= pagedList.TotalPages; i++)
            {
                TagBuilder tag = new TagBuilder("a");
                tag.InnerHtml = i.ToString();
                if (i == pagedList.CurrentPage) 
                    tag.AddCssClass("selected");
                else 
                    tag.Attributes.Add("href", pageUrl.Invoke(i));

                result.AppendLine(tag.ToString());
            }

            if (pagedList.HasNextPage) {
                TagBuilder tag = new TagBuilder("a");
                tag.InnerHtml = "next";
                tag.Attributes.Add("href", pageUrl.Invoke(pagedList.NextPage));
                result.AppendLine(tag.ToString());
            }

            return MvcHtmlString.Create(result.ToString());
        }
    }
}